package com.tencent.qcloud.tim.uikit.utils;

import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ClickableSpan;
import android.view.View;

import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.List;

/**
 * 创建者 zx
 * 创建时间 2021/2/24 14:57
 */
public class CustomMsgUtil {
    private final String TAG = "CustomMsgUtil";


    /**
     * 解析自定义消息
     *
     * @param msg
     * @return
     */
    public static CharSequence getMsgBoy(String msg, final OnTextClick onTextClick) {
        List<String> strings = getMsgList(msg);
        msg = msg.replaceAll("\\{", "");
        msg = msg.replaceAll("\\}", "");
        CharSequence charSequence = msg;
        for (final String s :
                strings) {
            int index = msg.indexOf(s);
            charSequence = ClickSpan(charSequence, index, index + s.length(), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onTextClick.onTextClick(s);
                }
            });
        }
        return charSequence;
    }


    public static List<String> getMsgList(String msg) {
        List<String> list = new ArrayList<String>();
        int start = 0;
        int startFlag = 0;
        int endFlag = 0;
        for (int i = 0; i < msg.length(); i++) {
            if (msg.charAt(i) == '{') {
                startFlag++;
                if (startFlag == endFlag + 1) {
                    start = i;
                }
            } else if (msg.charAt(i) == '}') {
                endFlag++;
                if (endFlag == startFlag) {
                    list.add(msg.substring(start + 1, i));
                }
            }
        }
        return list;
    }

    /**
     * 点击事件
     *
     * @param text
     * @param start
     * @param end
     * @param clickListener
     * @return
     */
    public static SpannableStringBuilder ClickSpan(CharSequence text, int start, int end, final View.OnClickListener clickListener) {
        SpannableStringBuilder ss = new SpannableStringBuilder(text);
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                if (clickListener != null) {
                    clickListener.onClick(widget);
                }
            }
        };
        ss.setSpan(clickableSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return ss;
    }


    public interface OnTextClick {
        void onTextClick(String text);
    }

}
